<?php
/**
 * Created by PhpStorm.
 * User: Digvijay
 * Date: 3/17/14
 * Time: 11:45 AM
 */
use Doctrine\ORM\Query\ResultSetMapping;

class MY_Controller extends CI_Controller {
    public static $em;
    public static $notification;

    function __construct() {
        parent::__construct();
        if (!$this->session->userdata('logged_in')) {
            redirect('login', 'refresh');
        } else {
            $sessionData = $this->session->userdata('logged_in');
            if ($sessionData != null && $sessionData['type'] != "ADMIN") {
                redirect('login', 'refresh');
            }
        }
        date_default_timezone_set('Asia/Kolkata');
        $this->em = $this->doctrine->em;
        $this->notification = $this->findById("Notification", 1);
    }

    function getLoggedInUser() {
        $loggedInUser = $this->session->userdata('logged_in');
        return $this->doctrine->em->getRepository("User")->find($loggedInUser);
    }

    function save($object) {
        $this->em = $this->doctrine->em;
        $this->em->persist($object);
        $this->em->flush();
    }

    function delete($object) {
        $this->em->remove($object);
        $this->em->flush();
    }

    function findById($objectName, $id) {
        return $this->em->getRepository($objectName)->find(intval($id));
    }

    function findAll($objectName) {
        return $this->em->getRepository($objectName)->findAll();
    }

    function findAllProduct(){
        $query = $this->em->createQuery("SELECT o FROM Product o WHERE o.active = true");
        return $query->getResult();
    }

    function findAllTopLevelCategories() {
        $query = $this->em->createQuery("SELECT o FROM Category o WHERE o.parent IS NULL");
        return $query->getResult();
    }

    function findByName($name, $object) {
        $query = $this->em->createQuery("SELECT o FROM " . $object . " o WHERE o.name = :name");
        $query->setParameter("name", $name);
        return $query->getResult();
    }

    function getProductByCategoryId($category) {
        $query = $this->em->createQuery("SELECT o FROM Product o WHERE o.category = :category and o.active = true");
        $query->setParameter("category", $category);
        return $query->getResult();
    }

    function getAllSubCategories($category) {
        $query = $this->em->createQuery("SELECT o FROM Category o WHERE o.parent = :category");
        $query->setParameter("category", $category);
        return $query->getResult();
    }

    function findAllOrdersByType($type) {
        $query = $this->em->createQuery("SELECT o FROM Order o WHERE o.status = :type order by o.orderDate desc");
        $query->setParameter("type", $type);
        return $query->getResult();
    }

    function findContentByType($type) {
        $query = $this->em->createQuery("SELECT o FROM Contents o WHERE o.type = :type");
        $query->setParameter("type", $type);
        return $query->getResult();
    }

    function getNoOfProducts(){
        $query = $this->em->createQuery("SELECT count(o) FROM Product o where o.active = true ");
        return $query->getSingleScalarResult();
    }

    function getNoOfOrdersByType($status) {
        $query = $this->em->createQuery("SELECT count(o) FROM Order o WHERE o.status = :status");
        $query->setParameter("status", $status);
        return $query->getSingleScalarResult();
    }

    function getNoAgentsByType($status) {
        $query = $this->em->createQuery("SELECT count(o) FROM Agency o WHERE o.status = :status");
        $query->setParameter("status", $status);
        return $query->getSingleScalarResult();
    }

    function getNoOfOrderByAgentType($clientType) {
        $query = $this->em->createQuery("SELECT count(o) FROM Order o WHERE o.status = :status AND o.id in (SELECT a.id FROM Agency a WHERE a.clientType = :clientType)");
        $query->setParameter("status", Order::ORDER_DELIVERED);
        $query->setParameter("clientType", $clientType);
        return $query->getSingleScalarResult();
    }

    function getSalesByMonth($month, $year) {
        $query = $this->em->createQuery("SELECT COUNT(o) FROM Order o WHERE YEAR(o.orderDate) = :inputYear AND MONTH(o.orderDate) = :inputMonth AND o.status = :status");
        $query->setParameter("inputYear", $year);
        $query->setParameter("inputMonth", $month + 1);
        $query->setParameter("status", Order::ORDER_DELIVERED);
        return $query->getSingleScalarResult();
    }

    function getAgentsByType($clientType) {
        $query = $this->em->createQuery("SELECT o FROM Agency o WHERE o.clientType = :clientType");
        $query->setParameter("clientType", $clientType);
        return $query->getResult();
    }

    function getSystemConfig($property){
        $query = $this->em->createQuery("SELECT o FROM Systemconfig o WHERE o.property = :property");
        $query->setParameter("property", $property);
        return $query->getResult()[0];
    }

    function sendMail($email = null, $subject = null, $msg = null) {
        $config = Array(
            'smtp_host' => 'cp-36.webhostbox.net',
            'smtp_user' => 'no-reply@anmolcards.net',
            'smtp_pass' => 'anmolcards',
            'smtp_port' => '465',
            'mailtype' => 'html',
            'validate' => 'TRUE',
            'charset' => 'iso-8859-1'
        );

        $this->load->library('email', $config);
        $this->email->set_newline("\r\n");
        $this->email->from("no-reply@anmolcards.net", "Anmol Cards");
        $this->email->to($email);
        $this->email->subject($subject);
        $this->email->message($msg);

        if ($this->email->send()) {
            return true;
        } else {
            return false;
        }
    }

    function sendOrderCancelNotificationMail($email = null, $subject = null, $msg) {
        $config = Array(
            'smtp_host' => 'cp-36.webhostbox.net',
            'smtp_user' => 'no-reply@anmolcards.net',
            'smtp_pass' => 'anmolcards',
            'smtp_port' => '465',
            'mailtype' => 'html',
            'validate' => 'TRUE',
            'charset' => 'iso-8859-1'
        );

        $this->load->library('email', $config);
        $this->email->set_newline("\r\n");
        $this->email->from("no-reply@anmolcards.net", "Anmol Cards");
        $this->email->to($email);
        $this->email->subject($subject);
        $this->email->message($this->load->view('orderCancelEmail',$msg,true));
        if ($this->email->send()) {
            return true;
        } else {
            return false;
        }
    }
}

class MY_Home extends CI_Controller {
    public static $em;
    public static $notification;

    function __construct() {
        parent::__construct();
        $this->em = $this->doctrine->em;
        date_default_timezone_set('Asia/Kolkata');
        $this->notification = $this->findById("Notification", 1);
    }

    function save($object) {
        $this->em = $this->doctrine->em;
        $this->em->persist($object);
        $this->em->flush();
    }

    function findById($objectName, $id) {
        return $this->em->getRepository($objectName)->find(intval($id));
    }

    function findAll($objectName) {
        return $this->em->getRepository($objectName)->findAll();
    }

    function findAllProduct(){
        $query = $this->em->createQuery("SELECT o FROM Product o WHERE o.active = true");
        return $query->getResult();
    }

    function findAgencyByEmail($email) {
        $query = $this->em->createQuery("SELECT o FROM Agency o WHERE o.email = :email");
        $query->setParameter("email", $email);
        return $query->getResult();
    }

    function isClientLoggedIn() {
        if ($this->session->userdata('logged_in')) {
            $sessionData = $this->session->userdata('logged_in');
            if ($sessionData['type'] == 'CLIENT' || ($sessionData['type'] == 'ANONYMOUS' && $sessionData['registered'] == true)) {
                $agency = $this->findById("Agency", $sessionData['agentId']);
                return $agency->getFirstName();
            }
        }
        return null;
    }

    function getDiscountForLoggedInUser() {
        if ($this->session->userdata('logged_in')) {
            $sessionData = $this->session->userdata('logged_in');
            if ($sessionData['type'] == 'CLIENT') {
                $agency = $this->findById("Agency", $sessionData['agentId']);
                return $agency->getDiscount();
            }
        }
        return 0;
    }

    function getCartDetails() {
        $noOfItems = 0;
        $totalRupees = 0;
        foreach ($this->cart->contents() as $item) {
            $noOfItems++;
            $totalRupees += $item["subtotal"];
        }
        $details = array("noOfItems" => $noOfItems, "totalRupees" => $totalRupees);
        return $details;
    }

    function findContentByType($type) {
        $query = $this->em->createQuery("SELECT o FROM Contents o WHERE o.type = :type");
        $query->setParameter("type", $type);
        return $query->getResult();
    }

    function sendMail($email = null, $subject = null, $msg = null) {
        $config = Array(
            'smtp_host' => 'cp-36.webhostbox.net',
            'smtp_user' => 'no-reply@anmolcards.net',
            'smtp_pass' => 'anmolcards',
            'smtp_port' => '465',
            'mailtype' => 'html',
            'validate' => 'TRUE',
            'charset' => 'iso-8859-1'
        );

        $this->load->library('email', $config);
        $this->email->set_newline("\r\n");
        $this->email->from("no-reply@anmolcards.net", "Anmol Cards");
        $this->email->to($email);
        $this->email->subject($subject);
        $this->email->message($msg);

        if ($this->email->send()) {
            return true;
        } else {
            return false;
        }
    }

    function sendOrderDetailsMail($email = null, $subject = null, $msg) {
        $config = Array(
            'smtp_host' => 'cp-36.webhostbox.net',
            'smtp_user' => 'no-reply@anmolcards.net',
            'smtp_pass' => 'anmolcards',
            'smtp_port' => '465',
            'mailtype' => 'html',
            'validate' => 'TRUE',
            'charset' => 'iso-8859-1'
        );

        $this->load->library('email', $config);
        $this->email->set_newline("\r\n");
        $this->email->from("no-reply@anmolcards.net", "Anmol Cards");
        $this->email->to($email);
        $this->email->subject($subject);
        $this->email->message($this->load->view('orderEmail',$msg,true));

        if ($this->email->send()) {
            return true;
        } else {
            return false;
        }
    }

    function sendOrderCancelNotificationMail($email = null, $subject = null, $msg) {
        $config = Array(
            'smtp_host' => 'cp-36.webhostbox.net',
            'smtp_user' => 'no-reply@anmolcards.net',
            'smtp_pass' => 'anmolcards',
            'smtp_port' => '465',
            'mailtype' => 'html',
            'validate' => 'TRUE',
            'charset' => 'iso-8859-1'
        );

        $this->load->library('email', $config);
        $this->email->set_newline("\r\n");
        $this->email->from("no-reply@anmolcards.net", "Anmol Cards");
        $this->email->to($email);
        $this->email->subject($subject);
        $this->email->message($this->load->view('orderCancelEmail',$msg,true));
        if ($this->email->send()) {
            return true;
        } else {
            return false;
        }
    }

    function getSystemConfig($property){
        $query = $this->em->createQuery("SELECT o FROM Systemconfig o WHERE o.property = :property");
        $query->setParameter("property", $property);
        return $query->getResult()[0];
    }

    function findAllPendingOrders(){
        $query = $this->em->createQuery("SELECT o FROM Order o WHERE o.status = :type order by o.orderDate desc");
        $query->setParameter("type", Order::ORDER_PENDING);
        return $query->getResult();
    }

    function getInventoryReport($quantity) {
        try{
            $query = $this->em->createQuery("Select p.name as productName, b.name as branchName, s.totalStock as currentStock from Product p JOIN p.stock s JOIN s.location b WHERE s.totalStock < :quantity AND p.active = true");
            $query->setParameter("quantity", $quantity);
            return $query->getArrayResult();
        }catch (Exception $e){
        }
    }
}
